import { Component, OnInit, Output, Input, ViewChild, EventEmitter } from '@angular/core';
import { PagesService } from 'services/pages.service';
import { UtilService } from 'services/util.service';
declare var layui: any;
declare var layer: any;
declare var $: any;

@Component({
  selector: 'app-bill-info',
  templateUrl: './bill-info.component.html',
  styleUrls: ['./bill-info.component.scss']
})
export class BillInfoComponent implements OnInit {

  constructor(public interfaceService: PagesService,public utilService: UtilService) { }

  @Output() private outer = new EventEmitter();
  @Input() module: any;
  @Input() tableId: any;
  @Input() tab_show: any;
  @Input() wdType: any;

  ngOnInit() {
  }

  /** 
   * 商品弹窗选择
   */
  @ViewChild('prodChild') prod: any;
  popup05_id
  popup05_url
  popup05_para
  popup05_judge // (0代表弹窗 1代表手动输入)
  popup05_show(id, para?): void {
    this.popup05_id = id
    this.popup05_para = para
    if (typeof (this.popup05_para) == "undefined") {
      this.popup05_judge = 0
    } else {
      this.popup05_judge = 1
    }
    if (this.popup05_id == 1) {
      this.popup05_url = "/erp/purchase/unitProdCls/billProdlist?judge=" + this.popup05_judge + "&switchUnitId=" + this.module.switchUnitId + this.wdType;
    }
    this.prod.popup01_show(this.popup05_url, this.popup05_para);
  }

  prodParent(e) {		//接收子组件传递过来的数据
    if (this.popup05_id == 1) {
      for (let i in e) {
        this.module.data2[i] = e[i] == null ? "" : e[i]
      }
    }
  }
  /**
   * 单据商品单条录入
   */
  prodQty = 1
  accumulation = false
  oneInfoSub() {
    if (!this.module.utilService.patrn.test(this.module.data2['prodCode'])) {
      layer.msg("商品代码不能为空！");
    } else {
      let pdata = {
        accumulation: this.accumulation,
        page: this.vice1_page,
        size: this.vice1_size,
        docDtlModels: [{ prodCode: this.module.data2['prodCode'], qty: this.prodQty }]
      }
      this.interfaceService.oneInfoAdd(this.interfaceService.postEdidField(this.module.info_moduleCode, pdata, this.module.fieldIndexParam, this.module.data1)).subscribe((data1: any) => {
        if (this.interfaceService.codeValidation(data1)) {
        layer.msg(data1.message);
        if (data1.code == 200) {
          this.module.indexIdValue = data1.object.prodId;
          this.vice1_page = data1.object.pageNum;
          this.module.data2['prodCode'] = '';
          this.prodQty = 1;
          this.vice1_talbe(this.vice1_page, this.vice1_size);
        }
      }
      });
    }
  }

  /** 
   * 商品多选穿梭框选择
   */
  @ViewChild('transferChild') transfer: any;
  popupTransfer_id
  popupTransfer_par
  popupTransfer_show(id): void {
    if (this.module.isEdit.update == 1) {
      this.popupTransfer_id = id
      if (this.popupTransfer_id == 1) {
        this.popupTransfer_par = "&switchUnitId=" + this.module.switchUnitId + this.wdType;
      }
      this.transfer.popup01_show(this.module.info_moduleCode, { page: this.vice1_page, size: this.vice1_size }, this.popupTransfer_par, this.module.fieldIndexParam, this.module.data1,this.module.switchUnitId,1);
    } else {
      layer.msg("该信息当前状态下不能新增！");
    }
  }

  transferParent(e) {		//接收子组件传递过来的数据
    this.interfaceService.moreInfoVis(e).subscribe((data1: any) => {
      if (this.interfaceService.codeValidation(data1)) {
      if (data1.code == 200) {
        this.interfaceService.moreInfoAdd(e).subscribe((data: any) => {
          if (this.interfaceService.codeValidation(data)) {
          layer.msg(data.message);
          if (data.code == 200) {
            this.module.indexIdValue = data.object.prodId;
            this.vice1_page = data.object.pageNum;
            this.vice1_talbe(this.vice1_page, this.vice1_size);
          }
        }
        });
      } else {
        layer.msg(data1.message);
      }
    }
    });
  }

  /** 
   * 表格上传下载
   */
  @ViewChild('tabUploadChild') tabUpload: any;
  tabUploadParent(e) {		//接收子组件传递过来的数据
    this.module.indexIdValue = e.prodId;
    this.vice1_page = e.pageNum;
    this.vice1_talbe(this.vice1_page, this.vice1_size);
  }
  /**
   * 单据明细保存
   */
  infoId;
  infoSub(id) {
    this.infoId = id
    if (this.infoId == 1) {
      this.interfaceService.infoSub(this.interfaceService.postEdidField(this.module.info_moduleCode, { page: this.vice1_page, size: this.vice1_size }, this.module.fieldIndexParam, this.module.data1)).subscribe((data1: any) => {
        if (this.interfaceService.codeValidation(data1)) {
        layer.msg(data1.message);
        if (data1.code == 200) {
          this.module.utilService.isCache[this.module.privIds] = false
          this.module.indexIdValue = data1.object.prodId;
          this.vice1_page = data1.object.pageNum;
          this.vice1_talbe(this.vice1_page, this.vice1_size);
        }
      }
      });
    }
  }
  /**
   * 单据明细取消
   */
  infoReset(id) {
    this.infoId = id
    if (this.infoId == 1) {
      this.interfaceService.infoReset(this.interfaceService.postEdidField(this.module.info_moduleCode, {}, this.module.fieldIndexParam, this.module.data1)).subscribe((data1: any) => {
        if (this.interfaceService.codeValidation(data1)) {
        layer.msg(data1.message);
        if (data1.code == 200) {
          this.module.utilService.isCache[this.module.privIds] = false
          this.module.indexIdValue = data1.object.prodId;
          this.vice1_page = data1.object.pageNum;
          this.vice1_talbe(this.vice1_page, this.vice1_size);
        }
      }
      });
    }
  }

  vice1_del(data) {
    var datas = [];
    datas[0] = data;
    this.interfaceService.infoDelete(this.interfaceService.postEdidFields(this.module.info_moduleCode, { page: this.vice1_page, size: this.vice1_size }, this.module.fieldIndexParam, this.module.fieldInfoParam, this.module.data1, datas)).subscribe((data1: any) => {
      if (this.interfaceService.codeValidation(data1)) {
      layer.msg(data1.message);
      if (data1.code == 200) {
        this.module.indexIdValue = data1.object.prodId;
        this.vice1_page = data1.object.pageNum;
        this.vice1_talbe(this.vice1_page, this.vice1_size);
      }
    }
    });
  }

  vice1_url;
  vice1_page;
  vice1_size;
  vice1_talbe(pageNum?, pageSize?) {
    if (JSON.stringify(this.module.tbdata) !== '{}') {
      this.interfaceService.postPage("/erp/common/fields/getdynamiclistfieldsbymodule/docdtl", this.interfaceService.newDtlVOField(this.module.info_moduleCode, { moduleCode: this.module.info_moduleCode, loadRule: this.module.info_loadRule }, this.module.fieldIndexParam, this.module.data1)).subscribe((data: any) => {
        if (this.interfaceService.codeValidation(data)) {
        if (data.code == 200) {
          this.module.field2 = this.module.utilService.filed_list3(data.object, 'barDemo2', 58);
          this.module.fieldInfoParam = this.interfaceService.fieldIndexParam(data.object);
          for (var i = 0; i < data.object.length; i++) {
            this.module.data2[data.object[i]["fieldValue"]] = ""
            this.module.data2_dis[data.object[i]["fieldValue"]] = true
          }
          if (typeof (pageNum) === 'undefined') {
            this.vice1_talbelist()
          } else {
            this.vice1_talbelist(pageNum)
          }
        } else {
          layer.msg(data.message);
        }
      }
      });
    }
  }

  /**
   * 明细汇总
   */
  infoTableSummary() {
    this.interfaceService.infoSummary(this.interfaceService.postEdidField(this.module.info_moduleCode, {}, this.module.fieldIndexParam, this.module.data1)).subscribe((data1: any) => {
      if (this.interfaceService.codeValidation(data1)) {
      if (data1.code == 200) {
        this.module.infoSummary = data1.object;
      } else {
        layer.msg(data1.message);
      }
    }
    });
  }

  vice1_talbelist(pageNum?): void {
    this.vice1_url = this.interfaceService.getEdidField(this.module.info_moduleCode, this.interfaceService.infoSelect, this.module.fieldIndexParam, this.module.data1)
    setTimeout(() => {
      layui.use(['table'], (obj) => {
        var  table = layui.table
        if (typeof (pageNum) === 'undefined') {
          var tab = this.module.utilService.getTable(this.vice1_url, '#' + this.module.vicel_tableId, this.module.field2, '#' + this.module.componentName + '_toolbarInfo', 1, 1)
        } else {
          var tab = this.module.utilService.getTable(this.vice1_url, '#' + this.module.vicel_tableId, this.module.field2, '#' + this.module.componentName + '_toolbarInfo', pageNum, 1)
        }
        tab["done"] = (res) => {
          this.vice1_size = $(this.module.componentName + ' div[lay-id=' + this.module.vicel_tableId + '] .layui-laypage-limits').find('option:selected').val();//每页数量
          this.vice1_page = $(this.module.componentName + ' div[lay-id=' + this.module.vicel_tableId + '] .layui-laypage-em').next().html();//当前页码
          this.vice1_size = typeof (this.vice1_size) === 'undefined' ? this.module.utilService.limit : this.vice1_size
          this.vice1_page = typeof (this.vice1_page) === 'undefined' ? 1 : this.vice1_page
          this.module.utilService.isCache[this.module.privIds] = res.operStatus;
          this.module.isDetail = true;
          if (this.module.utilService.isCache[this.module.privIds]) {
            $(this.module.componentName + ' div[lay-id=' + this.module.indexTableId + ']').css("pointer-events", "none");
          } else {
            $(this.module.componentName + ' div[lay-id=' + this.module.indexTableId + ']').css("pointer-events", "auto");
          }
          res.data.forEach((item, index) => {
            if (item.prodId === this.module.indexIdValue) {
              $("app-assembly-list .table2 .layui-table-box tbody tr[data-index='" + index + "']").addClass('layui-table-click').siblings().removeClass('layui-table-click');
            }
          });
          this.infoTableSummary();
          this.utilService.tdTitle()
        }
        table.render(tab);
        //监听行单击事件row   监听行双击事件rowDouble
        table.on('row(' + this.module.vicel_tableId + ')', (obj) => {
          obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');//标注选中样式
          $('.' + this.module.vicel_tableId + ' p.infoData').text(JSON.stringify(obj.data));
        });
        table.on('rowDouble(' + this.module.vicel_tableId + ')', (obj) => {
        });
        //监听单元格编辑
        table.on('edit(' + this.module.vicel_tableId + ')', (obj) => {
          var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
          var datas = [];
          datas[0] = data;
          this.interfaceService.infoUpdate(this.interfaceService.postdbEdidField(this.module.info_moduleCode, { page: this.vice1_page, size: this.vice1_size }, this.module.fieldIndexParam, this.module.fieldInfoParam, this.module.data1, datas, field, value)).subscribe((data1: any) => {
            if (this.interfaceService.codeValidation(data1)) {
            layer.msg(data1.message);
            if (data1.code == 200) {
              var infoData = data1.object.result
              for (var p in infoData) {
                $(this.module.componentName + ' div[lay-id=' + this.module.vicel_tableId + '] ' + obj.tr.selector + ' td[data-field=' + p + ']' + ' div.layui-table-cell').text(infoData[p] == null ? '' : infoData[p])
                $(this.module.componentName + ' div[lay-id=' + this.module.vicel_tableId + '] ' + obj.tr.selector + ' td[data-field=' + p + ']' + ' input').val(infoData[p] == null ? '' : infoData[p])
              }
              this.infoTableSummary();
            } else {
              var infoData = JSON.parse($('.' + this.module.vicel_tableId + ' p.infoData').text())
              for (var p in infoData) {
                $(this.module.componentName + ' div[lay-id=' + this.module.vicel_tableId + '] ' + obj.tr.selector + ' td[data-field=' + p + ']' + ' div.layui-table-cell').text(infoData[p] == null ? '' : infoData[p])
                $(this.module.componentName + ' div[lay-id=' + this.module.vicel_tableId + '] ' + obj.tr.selector + ' td[data-field=' + p + ']' + ' input').val(infoData[p] == null ? '' : infoData[p])
              }
            }
            this.module.utilService.isCache[this.module.privIds] = data1.object.operStatus;
          }
          });
        });
        //头工具栏事件
        table.on('toolbar(' + this.module.vicel_tableId + ')', (obj) => {
          var checkStatus = table.checkStatus(obj.config.id);
          switch (obj.event) {
            case 'data_output':
              const parm = this.interfaceService.postEdidField(this.module.info_moduleCode, {}, this.module.fieldIndexParam, this.module.data1);
              const parms = {
                docDtl: parm,
                dynamicList: { moduleCode: this.module.info_moduleCode, loadRule: this.module.info_loadRule, parameter: parm }
              }
              this.tabUpload.data_output(parms);
              break;
            case 'file_input':
              if (this.module.isEdit.update == 1) {
                this.tabUpload.upload_show(this.interfaceService.postEdidField(this.module.info_moduleCode, {}, this.module.fieldIndexParam, this.module.data1));
              } else {
                layer.msg("该信息当前状态下不能进行导入操作！");
              }
              break;
            case 'template_download':
              this.tabUpload.template_download(this.interfaceService.newDtlVOField(this.module.info_moduleCode, { moduleCode: this.module.info_moduleCode, loadRule: this.module.info_loadRule }, this.module.fieldIndexParam, this.module.data1));
              break;
          };
        });
        //监听行工具事件
        table.on('tool(' + this.module.vicel_tableId + ')', (obj) => {
          var data = obj.data;
          if (obj.event === 'del') {
            if (this.module.isEdit.update == 1) {
              layer.confirm('是否确定删除？', (index) => {
                layer.close(index);
                this.vice1_del(data);
              });
            } else {
              layer.msg("该信息当前状态下不能删除！");
            }
          }
        });
      });
    }, 50);
  }
//动态弹窗公用
  /**
   * 
   * @param id 弹窗标识
   * @param type 弹窗类型
   * @param key 弹窗动态列标识
   * @param title 弹窗文字
   * @param value 验证数值（可选参数，传递正常参数为验证数据模式）
   */
  popupId;
  @ViewChild('popupChild') popup: any;
  popupTable(id, type, key, title, value?): void {
    this.popupId = id;
    var judge = value === undefined ? 0 : 1;
    if (this.popupId === 1) {
      var parm =  "?1=1&judge=" + judge + "&switchUnitId=" + this.module.switchUnitId + this.wdType;
    }
    if (value) {
      this.popup.tableShow(key, parm,title, value);
    } else {
      this.popup.tableShow(key, parm,title);
    }
  }

  popupParent(e) {
    if (this.popupId === 1) {
        for (let i in e) {
          this.module.data2[i] = e[i] == null ? "" : e[i]
        }
    }
  }

}
